/**
 * 设备管理 Composable
 */
import { reactive, ref } from "vue"
import { ElMessage, ElMessageBox } from "element-plus"
import { getLoginDevices, logoutAllOtherDevices, logoutDevice } from "@/api/modules/device"

/**
 * 设备管理 Hook
 * @returns {Object}
 */
export function useDevice() {
  const loading = ref(false)
  const logoutAllLoading = ref(false)
  const logoutLoading = reactive({})
  const deviceList = ref([])
  const currentPage = ref(1)
  const pageSize = ref(10)
  const total = ref(0)

  /**
   * 加载设备列表
   */
  const loadDevices = async () => {
    loading.value = true
    try {
      const response = await getLoginDevices({
        pageNum: currentPage.value,
        pageSize: pageSize.value
      })

      if (response.code === 200) {
        deviceList.value = response.data.records || response.data.list || []
        total.value = response.data.total || 0
      }
    } catch (error) {
      console.error('加载登录设备失败:', error)
      ElMessage.error('加载登录设备失败')
    } finally {
      loading.value = false
    }
  }

  /**
   * 登出指定设备
   */
  const handleLogout = async (device) => {
    try {
      await ElMessageBox.confirm(
        `确定要登出设备"${device.deviceName}"吗？该设备将被强制下线。`,
        '确认登出',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )

      logoutLoading[device.id] = true
      const response = await logoutDevice(device.id)

      if (response.code === 200) {
        ElMessage.success('设备已登出')
        await loadDevices()
      }
    } catch (error) {
      if (error !== 'cancel') {
        console.error('登出设备失败:', error)
        ElMessage.error('登出设备失败')
      }
    } finally {
      logoutLoading[device.id] = false
    }
  }

  /**
   * 登出所有其他设备
   */
  const handleLogoutAll = async () => {
    try {
      await ElMessageBox.confirm(
        '确定要登出所有其他设备吗？除当前设备外的所有设备将被强制下线。',
        '确认登出',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )

      logoutAllLoading.value = true
      const response = await logoutAllOtherDevices()

      if (response.code === 200) {
        ElMessage.success('已登出所有其他设备')
        await loadDevices()
      }
    } catch (error) {
      if (error !== 'cancel') {
        console.error('登出所有设备失败:', error)
        ElMessage.error('登出所有设备失败')
      }
    } finally {
      logoutAllLoading.value = false
    }
  }

  return {
    loading,
    logoutAllLoading,
    logoutLoading,
    deviceList,
    currentPage,
    pageSize,
    total,
    loadDevices,
    handleLogout,
    handleLogoutAll
  }
}
